import { typeIs } from "@alrale/common-lib";
import { setAjaxType, setProtocol } from "./store";

export function fmtJSON(val) {
  if (!val) return val;
  try {
    return JSON.parse(val);
  } catch (error) {
    return val;
  }
}

export function headersToObject(target) {
  if (typeIs(target) != "array") return {};
  const headers = {};
  for (let i = 0; i < target.length; i++) {
    const { name, value } = target[i];
    headers[name] = value;
  }
  return headers;
}

export function windowReload() {
  if (!chrome || !chrome.devtools) return;
  chrome.devtools.inspectedWindow.eval(`window.location.reload()`);
}

export function logger(...args) {
  if (chrome && chrome.devtools)
    chrome.devtools.inspectedWindow.eval(`
      console.log(...${JSON.stringify(args)});
    `);
}

/**初始化storage */
export function initStore(command) {
  window[command] = function() {
    setAjaxType({ xhr: true, fetch: true });
    setProtocol({
      get: true,
      post: true,
      put: true,
      delete: true,
    });
  };
}
